/*
 * SPDX-FileCopyrightText: 2023-2024 Andrew Gunnerson
 * SPDX-License-Identifier: GPL-3.0-only
 */

package com.sanji.audio_test.rule

import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.core.os.BundleCompat
import androidx.core.view.MenuProvider
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.preference.Preference
import androidx.preference.PreferenceScreen
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.sanji.audio_test.PreferenceBaseFragment
import com.sanji.audio_test.Preferences
import com.sanji.audio_test.R
import kotlinx.coroutines.launch

/**
 * 录音规则Fragment
 * 用于显示和管理录音规则列表的界面片段
 */
class RecordRulesFragment : PreferenceBaseFragment(), Preference.OnPreferenceClickListener,
    RecordRulesAdapter.Listener {
    // 通过委托获取ViewModel实例
    private val viewModel: RecordRulesViewModel by viewModels()

    // 添加新规则的偏好设置项
    private lateinit var prefAddNewRule: Preference

    // 全局适配器，用于组合多个适配器
    private val globalAdapter = ConcatAdapter()
    // 规则适配器
    private lateinit var rulesAdapter: RecordRulesAdapter

    /**
     * 创建偏好设置
     */
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.record_rules_preferences, rootKey)

        val context = requireContext()

        prefAddNewRule = findPreference(Preferences.PREF_ADD_NEW_RULE)!!
        prefAddNewRule.onPreferenceClickListener = this

        rulesAdapter = RecordRulesAdapter(context, this)

        // 监听规则变化
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.rules.collect {
                    rulesAdapter.setDisplayableRules(it)
                }
            }
        }

        // 设置片段结果监听器，处理规则编辑器返回的结果
        setFragmentResultListener(RecordRuleEditorBottomSheet.TAG) { _, result ->
            val position = result.getInt(RecordRuleEditorBottomSheet.RESULT_POSITION)
            val recordRule = BundleCompat.getParcelable(
                result,
                RecordRuleEditorBottomSheet.RESULT_RECORD_RULE,
                RecordRule::class.java,
            )!!

            if (position >= 0) {
                viewModel.replaceRule(position, recordRule)
            } else {
                viewModel.addRule(recordRule)
            }
        }
    }

    /**
     * 视图创建完成后调用
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 添加菜单提供者
        requireActivity().addMenuProvider(object : MenuProvider {
            override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
                menuInflater.inflate(R.menu.record_rules, menu)
            }

            override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
                return when (menuItem.itemId) {
                    R.id.reset -> {
                        viewModel.reset()
                        true
                    }
                    else -> false
                }
            }
        }, viewLifecycleOwner, Lifecycle.State.RESUMED)
    }

    /**
     * 创建RecyclerView
     */
    override fun onCreateRecyclerView(
        inflater: LayoutInflater,
        parent: ViewGroup,
        savedInstanceState: Bundle?
    ): RecyclerView = super.onCreateRecyclerView(inflater, parent, savedInstanceState).apply {
        ItemTouchHelper(RecordRulesTouchHelperCallback(rulesAdapter)).attachToRecyclerView(this)
    }

    /**
     * 创建布局管理器
     */
    override fun onCreateLayoutManager(): RecyclerView.LayoutManager {
        return RecordRulesLayoutManager(requireContext(), globalAdapter)
    }

    /**
     * 创建适配器
     */
    override fun onCreateAdapter(preferenceScreen: PreferenceScreen): RecyclerView.Adapter<*> {
        globalAdapter.addAdapter(super.onCreateAdapter(preferenceScreen))
        globalAdapter.addAdapter(rulesAdapter)
        return globalAdapter
    }

    /**
     * 偏好设置项点击事件处理
     */
    override fun onPreferenceClick(preference: Preference): Boolean {
        when (preference) {
            prefAddNewRule -> {
                // 创建新的默认规则
                val newRule = RecordRule(
                    callNumber = RecordRule.CallNumber.Any,
                    callType = RecordRule.CallType.ANY,
                    simSlot = RecordRule.SimSlot.Any,
                    action = RecordRule.Action.SAVE,
                )

                // 显示规则编辑器底部弹窗
                RecordRuleEditorBottomSheet.newInstance(-1, newRule, false)
                    .show(parentFragmentManager.beginTransaction(), RecordRuleEditorBottomSheet.TAG)
                return true
            }
        }

        return false
    }

    /**
     * 规则变化处理
     * @param rules 更新后的规则列表
     */
    override fun onRulesChanged(rules: List<RecordRule>) {
        viewModel.replaceRules(rules)
    }

    /**
     * 规则选择处理
     * @param position 规则位置
     * @param rule 选中的规则
     * @param isDefault 是否为默认规则
     */
    override fun onRuleSelected(position: Int, rule: RecordRule, isDefault: Boolean) {
        // 显示规则编辑器底部弹窗
        RecordRuleEditorBottomSheet.newInstance(position, rule, isDefault)
            .show(parentFragmentManager.beginTransaction(), RecordRuleEditorBottomSheet.TAG)
    }
}